package com.example.springboottools.pic;

import com.aliyun.imagerecog20190930.models.RecognizeImageColorResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class RecognizeImageColor {
    public static com.aliyun.imagerecog20190930.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          初始化配置对象com.aliyun.teaopenapi.models.Config
          Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
         */
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "imagerecog.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imagerecog20190930.Client(config);
    }

    public static void main(String[] args) throws Exception {
        // 创建AccessKey ID和AccessKey Secret，请参见：https://help.aliyun.com/document_detail/175144.html
        // 如果您使用的是RAM用户的AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参见：https://help.aliyun.com/document_detail/145025.html
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
//        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
//        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        String accessKeyId = "LTAI4FykcchFoy1oGMA9Q32d";
        String accessKeySecret = "NbgDJ9syKIJVmjEkJ6ClrDVN4F3OQE";
        com.aliyun.imagerecog20190930.Client client = RecognizeImageColor.createClient(accessKeyId, accessKeySecret);
        // 场景一，使用本地文件
        InputStream inputStream = new FileInputStream(new File("C:\\Users\\SH102909\\Downloads\\createProducts (10)\\新建文件夹\\7701156568EA_5.jpg"));
        // 场景二，使用任意可访问的url
       // URL url = new URL("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imagerecog/RecognizeImageColor/RecognizeImageColor1.jpg");
       // InputStream inputStream = url.openConnection().getInputStream();
        com.aliyun.imagerecog20190930.models.RecognizeImageColorAdvanceRequest recognizeImageColorAdvanceRequest = new com.aliyun.imagerecog20190930.models.RecognizeImageColorAdvanceRequest()
                .setUrlObject(inputStream)
                .setColorCount(3);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            RecognizeImageColorResponse response = client.recognizeImageColorAdvance(recognizeImageColorAdvanceRequest, runtime);
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
        } catch (TeaException error) {
            // 获取整体报错信息
            System.out.println(com.aliyun.teautil.Common.toJSONString(error));
            // 获取单个字段
            System.out.println(error.getCode());
        }
    }
}
